define(["jquery","bootstrap","contextmenu",  "bbcare","fu/app/comm/comm",
	"scprit/nutrition/app/nutritionApplication/nutritionApplicationDetails.servers.js",
	"scprit/nutrition/app/nutritionApplication/nutritionApplicationDetails.ui.js",
	"jqprint", "migrate_jqprint"
	],function($,$bootstrap,$contextmenu, $bb,$comm,$servers,$ui, $jqprint){
	var event = {};

	/**
	 * 终止方案成功后的回调函数
	 */
	var ajaxStopSchemeCallBack = function(data,params){
		$bb.toastShow("停止方案成功！");
		detail(params.indexStage,params.indexCourse,params.ptSchemeId);
	}

	/**
	 * 终止方案
	 */
	var onStopScheme = function(){
		var data = $(this).data("params");
		$servers.ajaxStopScheme(data,ajaxStopSchemeCallBack);
	}

	/**
	 * 更换方案成功后的回调函数
	 */
	var ajaxChangeSchemeCallBack = function(data,className){
		$("." + className).modal('hide');
		detail(0,0,data.ptNtschemeId);
		$bb.toastShow("更换方案成功！");
	}
	/**
	 * 方案列表查询成功后的回调函数
	 */
	var ajaxSchemeListCallBack = function(data,params){
		var className = "changeSchemeModal",tit = "更换营养方案";
    	$comm.modal({
            "className": className,
            "tit": tit
        },function(){
        	$ui.schemeList({
				"dom": $("." + className + " .modal-body"),
				"list":data,
				"title":tit
			});
	    	$("." + className).modal('show');
	    	$("#changeSchemeBtn").unbind("click");
	    	$("#changeSchemeBtn").click(function(){
	    		var schemeVersionId = $("#selectChangeScheme").val();
				var params1 ={};
				if(params.status != "4"){
					$bb.toastConfirmShow(function(){
						params1 = {"ptSchemeId":params.ptSchemeId,"userId":params.userId,"schemeVersionId":schemeVersionId};
						$servers.ajaxChangeScheme(params1,ajaxChangeSchemeCallBack,className);
					},'',"更换方案后，该用户之前应用的方案将终止，继续更换？");
				}else{
					$bb.toastConfirmShow(function(){
						params1 = {"useType":"2","userId":params.userId,"schemeVersionId":schemeVersionId};
						$servers.ajaxSchemeUsed(params1,ajaxChangeSchemeCallBack,className);
					},'',"更换方案后，该用户之前应用的方案将终止，继续更换？");
				}
	    	});
        });
	}
	/**
	 * 更换方案
	 */
	var onChangeScheme = function(){
		var data = $(this).data("params");
		$servers.ajaxSchemeList(data,ajaxSchemeListCallBack);
	}

	/**
	 * 启用阶段成功后的回调函数
	 */
	var ajaxStartStageCallBack = function(data,params){
		$bb.toastShow("启用该阶段成功！");
		detail(params.indexStage,params.indexCourse,params.ptSchemeId);
	}

	/**
	 * 启用阶段
	 */
	var onStartStage = function(){
		var data = $(this).data("params");
		$servers.ajaxStartStage(data,ajaxStartStageCallBack);
	}

	/**
	 * 启用疗程成功后的回调函数
	 */
	var ajaxStartCourseCallBack = function(data,params,className){
		$("." + className).modal('hide');
		$bb.toastShow("启用该疗程成功！");
		detail(params.indexStage,params.indexCourse,params.ptSchemeId);
	}

	/**
	 * 启用疗程
	 */
	var onStartCourse = function(){
		var data = $(this).data("params");
		var className = "startCourseModal";
		$comm.modal({
            "className": className,
            "tit": "启用疗程"
        },function(){
        	$ui.startCourseStartTime({
				"dom": $("." + className + " .modal-body"),
				"minDate":$comm.getCurTime().date
			});
	    	$("." + className).modal('show');
	    	$("#startCourseStartTimeBtn").unbind("click");
	    	$("#startCourseStartTimeBtn").click(function(){
	    		var startDate = $("#startDate").val();
				if(startDate){
					params = $.extend(data,{"startDate":startDate});
					$servers.ajaxStartCourse(params,ajaxStartCourseCallBack,className);
				}else{
					$bb.toastShow("请先选择疗程开始时间");
				}
	    	});
        });
	}

	var onPrint = function() {
		var date = new Date()
		var year = date.getFullYear()
		var month = date.getMonth() + 1
		var day = date.getDate()
		var hour = date.getHours()
		var min = date.getMinutes()
		var sec = date.getSeconds()
		$('#time').text(year + '年' + month + '月' + day + '日 ' + addZore(hour) + ':' + addZore(min) + ':' + addZore(sec))
		$('#printContent').jqprint({
			debug: false,
			importCSS: true,
			printContainer: true,
			operaSupport: true
		})
	}

	var addZore = function (num) {
		return num < 10 ? '0' + num : num
	}

	/**
	 * 请求停用疗程成功后的回调函数
	 */
	var ajaxStopCourseCallBack =function(data,params){
		$bb.toastShow("停用该疗程成功！");
		detail(params.indexStage,params.indexCourse,params.ptSchemeId);
	}

	/**
	 * 停用疗程
	 */
	var onStopCourse = function(){
		var params = $(this).data("params");
		$servers.ajaxStopCourse(params,ajaxStopCourseCallBack);
	}

	/**
	 * 编辑饮食量成功后的回调函数
	 */
	var ajaxAmountModifyCallBack = function(params,className){
		$("." + className).modal('hide');
		var indexStage = $("#stagesCourseBox .stages-list ul li.active").index();
		var indexCourse = $("#stagesCourseBox .course-list-group ul li.active").index();
    	detail(indexStage,indexCourse);
    	var tip = params.type == "1" ? "营养疗程计划饮食量编辑成功！" : "营养疗程实际饮食量编辑成功！";
    	$bb.toastShow(tip);
	}

	/**
	 * 编辑饮食量(实际、计划)
	 */
	var onEditAmount = function(){
		var data = $(this).data();
		var tit = data.type == "1" ? "编辑计划饮食量" : "编辑实际饮食量";
		var className = "editAmountModal";
    	$comm.modal({
            "className": className,
            "tit": tit
        },function(){
        	$ui.editAmountInit({ 
	    		"dom": $("." + className + " .modal-body"),
	    		"value":data.value
	    	});
	    	$("." + className).modal('show');
	    	$("#editActualAmountBtn").unbind("click");
	    	$("#editActualAmountBtn").click(function(){
	    		var amount = $("#editActualAmount").val();
				if(amount*1 > 0){
					var params = {
						"amount":amount,
						"situationIds":[data.situationId],
						"type":data.type
					};
					$servers.ajaxAmountModify(params,ajaxAmountModifyCallBack,className);
				}else{
					$bb.toastShow("请输入大于0的值",1500);
				}

	    	});
        });
	}

	/**
	 * 请求饮食量修改记录成功后的回调函数
	 */
	var ajaxModifylistCallBack = function(data){
    	var className = "editRecordModal";
    	$comm.modal({
            "className": className,
            "tit": "修改记录"
        },function(){
        	$ui.modifylistInit({ 
	    		"dom": $("." + className + " .modal-body"),
	    		"list":data
	    	});
	    	$("." + className).modal('show');
        });
	} 

	/**
	 * 饮食量修改记录
	 */
	var onModifylist = function(){
		var situationId = $(this).data("situationId");
		$servers.ajaxModifylist(situationId,ajaxModifylistCallBack);
	}

	var renderPrint = function (data) {
		$('#table1').empty()
		$('#table2').empty()
		$('#tbody').empty()
		$('#current')
		// 1.添加 早 中 晚
		var table1 = '<th rowspan="2" style="width: 50px;">天数共' + data.situations.length + '天</th>'
		var table2 = ''
		var tbody = ''
		data.periodHeads.forEach(function (item, index) {
			var th = '<th colspan="'+ (item.foods.length  - 1 ) +'">'+ item.periodName + '('+ item.time +')</th>'
			table1 += th
			item.foods.forEach(function (food) {
				if (food.foodName == '其他') return
				var th2 = '<th>' + food.foodName + (food.foodUnit ? '(' + food.foodUnit + ')' : '') + '</th>'
				table2 += th2
			})
		})
		table1 += '<th colspan="' + data.courseNutritions.length + '">推荐营养素</th>'
		// 2.营养素
		data.courseNutritions.forEach(function (item) {
			var th2 = '<th>' + item.nutrientsName + '(' + item.nutrientsUnit + ')</th>'
			table2 += th2
		})
		// 3.值的加入
		data.situations.forEach(function (item) {
			tbody += '<tr><td>'+ item.day +'</td>'
			item.foodList.forEach(function (food) {
				if (!food.defaultAmount) return
				tbody += '<td>'+  (food.defaultAmount ? food.defaultAmount : '')  +'</td>'
			})
			item.nutrientList.forEach(function (nutrent) {
				tbody += '<td>'+ nutrent.averageAmount + '</td>'
			})
			tbody += '</tr>'
		})

		$('#table1').append(table1)
		$('#table2').append(table2)
		$('#tbody').append(tbody)
	}

	var renderUserInfo = function (data) {
		$('#userName').text(data.userName)
		$('#age').text(data.age)
		$('#phone').text(data.phoneNo)

		var apps
		try {
			apps = JSON.parse(sessionStorage.getItem('account'))
			$('#doctorName').text(apps.alias)
			var hosiName = $('.tenant_name').text()
			$('#hosiName').text(hosiName)
		}catch(err) {}
	}

	/**
	 * 查询疗程详情成功后的回调函数
	 */
	var ajaxCourseDetailCallBack = function(data){
		data.totalDays = data.situations.length;
		$ui.courseTableTheadInit({
			"id":"courseTableThead",
			"data":data
		});
		$ui.courseTableTbodyInit({
			"id":"courseTableTbody",
			"data":data
		});
		renderPrint(data)
        $('td.can-modify').contextmenu({
        	target:'#context-menu', 
			before: function(e,context) {
				var flag = $(e.currentTarget).attr("flag");  // 1 或 2
				var foodData =  data.situations[$(e.currentTarget).parents("tr").index()].foodList[$(e.currentTarget).index()-2].data;
				if(flag == 3){
					if(foodData.length){
						$ui.contextMenu({
							"id":"context-menu",
							"flag":flag,
							"data": foodData
						});
					}else{
						$("#context-menu").empty();
					}
				}else{
					$ui.contextMenu({
						"id":"context-menu",
						"flag":flag
					});
				}
				var situationId = $(e.currentTarget).attr("situationId");
				var actualAmount = $(e.currentTarget).find(".actual-amount").html();
				var defaultAmount = $(e.currentTarget).find(".default-amount").html();
				// 编辑实际饮食量
				if( flag == 1 ){
					$("#context-menu .editActualAmount").unbind("click");
					$("#context-menu .editActualAmount").data({"situationId":situationId,"value":actualAmount,"type":"2"});
					$("#context-menu .editActualAmount").click(onEditAmount);
				}
			    // 编辑计划饮食量
			    $("#context-menu .editDefaultAmount").unbind("click");
				$("#context-menu .editDefaultAmount").data({"situationId":situationId,"value":defaultAmount,"type":"1"});
			    $("#context-menu .editDefaultAmount").click(onEditAmount);
			    // 数据溯源
			    $("#context-menu .modifylist").unbind("click");
			    $("#context-menu .modifylist").data({"situationId":situationId});
			    $("#context-menu .modifylist").click(onModifylist);
			},
			onItem: function(context,e){}
        });
	}

	/**
	 * 点击疗程
	 */
	var onCourseSelect = function(){
		var data = $(this).data();
		var indexCourse = $(this).index();
		var indexStage = $(this).parents(".course-list-group").index();
		var $stage = $(".stages-list li").eq(indexStage);
		$stage.addClass("active").siblings().removeClass("active");
		$(".course-list li.active").removeClass("active");
		$(this).addClass("active");
		// 获取当前页面的阶段id 和疗程id 
		var currSchemeId = $("#schemeName .ptScheme-name").attr("ptSchemeId");
		var currStageId = $(this).attr("pStageId");
		var currCourseId = $(this).attr("ptCourseId");
		// 页面显示的当前阶段、当前疗程
		var currStageDom = $stage.html() + "（<em>" + $servers.getTipByStatus( $stage.attr("status") ) + "</em>）";
		var currCourseDom = $(this).html() + "（<em>"+ $servers.getTipByStatus( $(this).attr("status") ) +"</em>）";
		$("#schemeName .curr-stage").html( currStageDom ).attr("ptStageId",currStageId);
		$("#schemeName .curr-course").html( currCourseDom ).attr("ptCourseId",currCourseId);
		// 按钮
		var handleParams = $servers.handleOperateSchemeBtnGroup({
        	"status":data.status,
			"list":data.ptStages,
			"currStageId":currStageId,
			"currCourseId":currCourseId
        });
		var topbars = [];
        if(handleParams.stageStatus == "2"){
        	if(handleParams.courseStatus == "2"){
        		topbars.push({
		            "icon":"fa fa-ban",
		            "name":"停用疗程",
		            "callback":onStopCourse,
		            "params":{"indexStage":indexStage,"indexCourse":indexCourse,"ptSchemeId":currSchemeId,"ptCourseId":currCourseId}
		        });
        	}else if(handleParams.courseStatus == "1"){
        		topbars.push({
		            "icon":"fa fa-clock-o",
		            "name":"启用疗程",
		            "callback":onStartCourse,
		            "params":{"indexStage":indexStage,"indexCourse":indexCourse,"ptSchemeId":currSchemeId,"ptCourseId":currCourseId}
		        });
        	} 
        }else if(handleParams.stageStatus == "1"){
        	topbars.push({
	            "icon":"fa fa-clock-o",
	            "name":"启用阶段",
	            "callback":onStartStage,
	            "params":{"indexStage":indexStage,"indexCourse":indexCourse,"userId":data.userId,"ptSchemeId":currSchemeId,"ptStageId":currStageId}
	        });
        }
		var name = "更换方案",icon = "fa fa-exchange";
        topbars.push({
            "icon":icon,
            "name":name,
            "callback":onChangeScheme,
            "params":{"userId":data.userId,"ptSchemeId":currSchemeId,"status":data.status}
        });
        if(handleParams.status == "1"){
        	topbars.push({
                "icon":"fa fa-ban",
                "name":"停止方案",
                "callback":onStopScheme,
                "params":{"indexStage":indexStage,"indexCourse":indexCourse,"userId":data.userId,"ptSchemeId":currSchemeId}
            });
		}
		// 固定添加打印方案
		topbars.push({
			icon: "fa fa-print",
			name: '打印方案',
			callback: onPrint
		})
        $bb.toolbar(topbars);
		// 请求表格数据
		var params = {
			"ptCourseId":currCourseId,
			"userId":data.userId
		}
		$servers.ajaxCourseDetail(params,ajaxCourseDetailCallBack);
	}

	/**
	 * 点击阶段
	 */
	var onStageSelect = function(){
		var index = $(this).index();
		var data = $(this).data("data");
		var indexCourse = $(this).data("indexCourse");
		$("#stagesCourseBox li.course-list-group").eq(index).find("ul li").unbind("click");
		$("#stagesCourseBox li.course-list-group").eq(index).find("ul li").data(data);
		$("#stagesCourseBox li.course-list-group").eq(index).find("ul li").click(onCourseSelect);
		$("#stagesCourseBox li.course-list-group").eq(index).find("ul li").eq(indexCourse).click();
	}

	/**
	 * 患者方案内容查询成功后的回调函数
	 */
	var ajaxDetailCallBack = function(data,ptSchemeId,phoneNo,indexStage,indexCourse){
		data.phoneNo = phoneNo;
		$ui.basicInfoInit({
			"id":"basicInfo",
			"data":data
		});
		renderUserInfo(data)
		// 启用阶段、启用疗程
		var usedStage = $servers.getUsedStage(data.ptStages) ? $servers.getUsedStage(data.ptStages) : "";
		var usedCourse = $servers.getUsedCourse(data.ptStages) ? $servers.getUsedCourse(data.ptStages) : "";
		// 启用疗程的渲染
		$('#current').text(usedStage.ptStageName)

		
		$ui.schemeNameInit({
			"id":"schemeName",
			"ptSchemeId":ptSchemeId,
			"ptSchemeName":data.ptSchemeName,
			"status":data.status,
			"usedStage":usedStage.ptStageName,
			"usedCourse":usedCourse.ptCourseName
		});
		$ui.stageNavbarInit({
			"id":"stagesCourseBox",
			"list":data.ptStages
		});
		// 悬浮navbar
		$("#stagesCourseBox .stages-box-close").unbind("click");
		$("#stagesCourseBox .stages-box-close").click(function(){
			$("#stagesCourseBox .stages-unfold").hide();
			$("#stagesCourseBox .stages-fold").show();
		});
		$("#stagesCourseBox .stages-fold").unbind("click");
		$("#stagesCourseBox .stages-fold").click(function(){
			$("#stagesCourseBox .stages-fold").hide();
			$("#stagesCourseBox .stages-unfold").show();
		});
		// 点击阶段进行切换
		$("#stagesCourseBox .stages-list li").unbind("click");
		$("#stagesCourseBox .stages-list li").data({"data":data,"indexCourse":indexCourse});
		$("#stagesCourseBox .stages-list li").click(onStageSelect);
		$("#stagesCourseBox .stages-list li").eq(indexStage).click();

		

	}

	var detail = function(indexStage,indexCourse,ptSchemeId){
		var params = $servers.getPageParams();
		if(ptSchemeId) params = $.extend(params,{"ptSchemeId":ptSchemeId});
		$servers.ajaxDetail(params,indexStage,indexCourse,ajaxDetailCallBack);
	}
	event.detail = function(indexStage,indexCourse,ptSchemeId){
		detail(indexStage,indexCourse,ptSchemeId);
	}

	return event;
});